package de.mfits.fireflyplayer.storage;

import net.firefly.client.model.data.Song;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper extends SQLiteOpenHelper {
  public static final String SONGS = "songs";

  public static final String ID = "_id";
  public static final String PART_OF_A_COMPILATION = "part_of_a_compilation";
  public static final String GENRE = "genre";
  public static final String ARTIST_ALBUM = "artist_album";
  public static final String ARTIST = "artist";
  public static final String ALBUM = "album";
  public static final String YEAR = "year";
  public static final String TITLE = "title";
  public static final String DISC_NUMBER = "disc_number";
  public static final String TRACK_NUMBER = "track_number";
  public static final String SIZE = "size";
  public static final String TIME = "time";
  public static final String TYPE = "type";

  public DbHelper(Context context) {
    super(context, "songs", null, 2);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table songs (" + ID + " int primarykey, " + PART_OF_A_COMPILATION
        + " int(1), " + GENRE + " varchar(64), " + ARTIST_ALBUM + " varchar(64), " + ARTIST
        + " varchar(64), " + ALBUM + " varchar(64), " + YEAR + " varchar(64), " + TITLE
        + " varchar(64), " + DISC_NUMBER + " varchar(64), " + TRACK_NUMBER + " varchar(64), "
        + SIZE + " int, " + TIME + " int, " + TYPE + " varchar(64));");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table songs");
    onCreate(db);
  }

  public Song loadSong(int id) {
    Song song = null;

    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.query(SONGS, new String[] { PART_OF_A_COMPILATION, GENRE, ARTIST_ALBUM,
        ARTIST, ALBUM, YEAR, TITLE, DISC_NUMBER, TRACK_NUMBER, SIZE, TIME, TYPE }, ID + "=?",
        new String[] { Integer.toString(id) }, null, null, null);

    if (cursor.moveToFirst()) {
      song = new Song();

      int col = 0;
      song.setPartOfACompilation(cursor.getInt(col++) != 0);
      song.setGenre(cursor.getString(col++));
      song.setArtistAlbum(cursor.getString(col++));
      song.setArtist(cursor.getString(col++));
      song.setAlbum(cursor.getString(col++));
      song.setYear(cursor.getString(col++));
      song.setTitle(cursor.getString(1));
      song.setDiscNumber(cursor.getString(col++));
      song.setTrackNumber(cursor.getString(col++));
      song.setSize(cursor.getInt(col++));
      song.setTime(cursor.getInt(col++));
      song.setType(cursor.getString(col++));
    }

    db.close();

    return song;
  }
}
